package com.zenithmind.news.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * WebSocket订阅管理器 - 遵循单一职责原则
 * 专门负责用户的订阅关系管理
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Component
public class WebSocketSubscriptionManager {

    // 存储分类订阅关系 - 分类ID -> 用户ID集合
    private final Map<String, CopyOnWriteArraySet<String>> categorySubscribers = new ConcurrentHashMap<>();
    
    // 存储标签订阅关系 - 标签 -> 用户ID集合
    private final Map<String, CopyOnWriteArraySet<String>> tagSubscribers = new ConcurrentHashMap<>();

    /**
     * 订阅分类
     */
    public void subscribeCategory(String userId, String categoryId) {
        categorySubscribers.computeIfAbsent(categoryId, k -> new CopyOnWriteArraySet<>()).add(userId);
        log.info("用户 {} 订阅了分类 {}", userId, categoryId);
    }

    /**
     * 取消订阅分类
     */
    public void unsubscribeCategory(String userId, String categoryId) {
        CopyOnWriteArraySet<String> subscribers = categorySubscribers.get(categoryId);
        if (subscribers != null) {
            subscribers.remove(userId);
            log.info("用户 {} 取消订阅了分类 {}", userId, categoryId);
        }
    }

    /**
     * 订阅标签
     */
    public void subscribeTag(String userId, String tag) {
        tagSubscribers.computeIfAbsent(tag, k -> new CopyOnWriteArraySet<>()).add(userId);
        log.info("用户 {} 订阅了标签 {}", userId, tag);
    }

    /**
     * 取消订阅标签
     */
    public void unsubscribeTag(String userId, String tag) {
        CopyOnWriteArraySet<String> subscribers = tagSubscribers.get(tag);
        if (subscribers != null) {
            subscribers.remove(userId);
            log.info("用户 {} 取消订阅了标签 {}", userId, tag);
        }
    }

    /**
     * 获取分类订阅者
     */
    public CopyOnWriteArraySet<String> getCategorySubscribers(String categoryId) {
        return categorySubscribers.get(categoryId);
    }

    /**
     * 获取标签订阅者
     */
    public CopyOnWriteArraySet<String> getTagSubscribers(String tag) {
        return tagSubscribers.get(tag);
    }

    /**
     * 移除用户的所有订阅
     */
    public void removeUserSubscriptions(String userId) {
        // 移除分类订阅
        categorySubscribers.values().forEach(subscribers -> subscribers.remove(userId));
        
        // 移除标签订阅
        tagSubscribers.values().forEach(subscribers -> subscribers.remove(userId));
        
        log.info("移除用户 {} 的所有订阅", userId);
    }

    /**
     * 批量订阅分类
     */
    public void batchSubscribeCategories(String userId, String[] categoryIds) {
        for (String categoryId : categoryIds) {
            subscribeCategory(userId, categoryId);
        }
    }

    /**
     * 批量订阅标签
     */
    public void batchSubscribeTags(String userId, String[] tags) {
        for (String tag : tags) {
            subscribeTag(userId, tag);
        }
    }
}
